package coom.zwj.reggie.contorller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import coom.zwj.reggie.common.R;
import coom.zwj.reggie.dto.DishDto;
import coom.zwj.reggie.entity.Category;
import coom.zwj.reggie.entity.Dish;
import coom.zwj.reggie.entity.DishFlavor;
import coom.zwj.reggie.service.CategoryService;
import coom.zwj.reggie.service.DishFlavorService;
import coom.zwj.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理所有菜品的缓存数据
        redisTemplate.delete(redisTemplate.keys("dish_*"));
        return R.success("新增成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page");
        //先根据页面信息查询到菜品的page
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //准备一个dishDto的page
        Page<DishDto> dishDtoPage = new Page<>();
        //完成装dish对象的page的查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //条件
        dishLambdaQueryWrapper.eq(name != null, Dish::getName, name);
        //排序
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, dishLambdaQueryWrapper);
        //将除records的属性拷贝到dishDtoPage里
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //取出dishPage里的records准备进行操作
        List<Dish> records = dishPage.getRecords();
        //遍历records 操作后获得新的dishDtoList
        List<DishDto> dishDtoList = records.stream().map((item) -> {
            //创建一个新的dto
            DishDto dishDto = new DishDto();
            //将当前成员的属性复制到dto里
            BeanUtils.copyProperties(item, dishDto);
            //取出当前成员所属的分类id
            Long id = item.getCategoryId();
            //根据id获取菜品名称
            Category category = categoryService.getById(id);
            //如果菜品名称不为空,将其赋值给dto
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            //返回操作完成的dto
            return dishDto;
        }).collect(Collectors.toList());
        //将获取的dishDtoList放入dishDtoPage的records中
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id获取菜品及口味
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        log.info("get id:{}", id);
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清理所有菜品的缓存数据
        redisTemplate.delete(redisTemplate.keys("dish_*"));
        return R.success("修改成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        log.info("根据条件查询对应的菜品数据");
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据CategoryId查询dish表对应信息
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //筛选状态为起售的dish
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        //排序
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);
        return R.success(dishList);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info("根据条件查询对应的菜品数据");

        List<DishDto> dishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据CategoryId查询dish表对应信息
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //筛选状态为起售的dish
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        //排序
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);
        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if (byId != null) {
                String name = byId.getName();
                dishDto.setCategoryName(name);
            }
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(list);
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
